<template>
  <div>
    <div class="mendian" v-if="flag">
      <!--        <h1>门店管理组件</h1>-->
      <div class="top">
        <span
          :class="{ upDown: k == index }"
          @click="clickUpDown(k)"
          v-for="(v, k) in upDownArr"
          :key="k"
          style="margin: 10px"
          >{{ v }}</span
        >
      </div>
      <div class="input">
        <div>
          <span>门店名称：</span>
          <el-input
            class="shuru"
            v-model="inputmendain"
            placeholder="请输入内容"
            >{{ inputmendain }}</el-input
          >
        </div>
        <div>
          <span>门店手机号：</span>
          <el-input
            class="shuru"
            v-model="mendainphone"
            placeholder="请输入内容"
            >{{ mendainphone }}</el-input
          >
        </div>

        <div class="block">
          <span class="demonstration">创建时间：</span>
          <el-date-picker
            v-model="value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
          <el-button style="margin-left: 10px" @click="search" type="primary"
            >搜索</el-button
          >
        </div>
      </div>

      <el-button
        type="primary"
        style="margin-bottom: 20px"
        @click="dialogFormVisible = true"
        >门店新增</el-button
      >

      <el-dialog title="门店新增" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="门店名称" :label-width="formLabelWidth">
            <el-input v-model="form.mendianname" autocomplete="off">{{
              form.mendianname
            }}</el-input>
          </el-form-item>
          <el-form-item label="门店头像" :label-width="formLabelWidth">
            <div style="height: 40px">
              <el-upload
                class="upload-demo"
                action="/upload/image"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
              >
                <div size="small" type="primary">+</div>
              </el-upload>
              <!--                        <el-input v-model="imageUrl" placeholder="请上传图片"></el-input>-->
              <img
                v-if="imageUrl"
                :src="imageUrl"
                alt="Uploaded Image"
                style="max-width: 100%; max-height: 200px"
              />
            </div>
          </el-form-item>
          <el-form-item label="门店手机号" :label-width="formLabelWidth">
            <el-input v-model="form.phonee" autocomplete="off">{{
              form.phonee
            }}</el-input>
          </el-form-item>
          <el-form-item label="所属地区" :label-width="formLabelWidth">
            <el-cascader
              :options="addressAll"
              clearable
              v-model="address"
              :props="{ value: 'label' }"
            ></el-cascader>

            <h1>{{ address.join("") }}</h1>
          </el-form-item>

          <el-form-item :label-width="formLabelWidth">
            <el-input
              v-model="form.date1"
              placeholder="请填写详细地址"
              autocomplete="off"
              >{{ form.date1 }}</el-input
            >
          </el-form-item>

          <el-form-item label="门店坐标" :label-width="formLabelWidth">
            <el-button @click="huoquposition" :plain="true">获取位置</el-button>
            <span>&nbsp;&nbsp;{{ form.weizhi }}</span>
          </el-form-item>
          <el-form-item label="营业时间" :label-width="formLabelWidth">
            <el-input v-model="form.openingHours" autocomplete="off">{{
              form.openingHours
            }}</el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="isok">确 定</el-button>
        </div>
      </el-dialog>
      <template>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :header-cell-style="{
            'background-color': 'rgb(24, 144, 255)',
            color: 'white',
            'text-align': ' center',
          }"
          :cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column fixed prop="shopName" label="门店">
          </el-table-column>
          <el-table-column fixed prop="shopId" label="ID"> </el-table-column>
          <el-table-column prop="shopPhone" label="门店手机号">
          </el-table-column>
          <el-table-column prop="shopAddress" label="门店地址">
          </el-table-column>
          <el-table-column prop="shopDescribe" label="营业时间">
          </el-table-column>
          <el-table-column prop="concernStatus" label="关联小区">
          </el-table-column>

          <el-table-column prop="shopOrderCount" label="订单总数">
          </el-table-column>
          <el-table-column prop="createTime" label="提交方式">
          </el-table-column>
          <el-table-column fixed="right" label="状态">
            <template slot-scope="scope1">
              <el-button type="text" size="small" @click="">上架中 </el-button>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template slot-scope="scope2">
              <el-button
                type="text"
                size="small"
                @click="shopManager(scope2.row)"
                >门店管理
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="bianjixiaoquIndex(scope2.row)"
                >修改门店资料
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-dialog title="编辑门店" :visible.sync="bianjixiaoqu">
        <el-form :model="form2">
          <el-form-item label="门店名称" :label-width="formLabelWidth">
            <el-input v-model="form2.mendianname" autocomplete="off">{{
              form2.mendianname
            }}</el-input>
          </el-form-item>
          <el-form-item label="门店头像" :label-width="formLabelWidth">
            <div style="height: 40px">
              <el-upload
                class="upload-demo"
                action="/upload/image"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
              >
                <div size="small" type="primary">+</div>
              </el-upload>
              <!--                        <el-input v-model="imageUrl" placeholder="请上传图片"></el-input>-->
              <img
                v-if="imageUrl"
                :src="imageUrl"
                alt="Uploaded Image"
                style="max-width: 100%; max-height: 200px"
              />
            </div>
          </el-form-item>
          <el-form-item label="门店手机号" :label-width="formLabelWidth">
            <el-input v-model="form2.phonee" autocomplete="off">{{
              form2.phonee
            }}</el-input>
          </el-form-item>
          <el-form-item label="所属地区" :label-width="formLabelWidth">
            <el-cascader
              :options="addressAll"
              clearable
              v-model="form2.address"
              :props="{ value: 'label' }"
            ></el-cascader>

            <h1>{{ form2.address.join("") }}</h1>
          </el-form-item>

          <el-form-item :label-width="formLabelWidth">
            <el-input
              v-model="form2.date1"
              placeholder="请填写详细地址"
              autocomplete="off"
              >{{ form2.date1 }}</el-input
            >
          </el-form-item>

          <el-form-item label="门店坐标" :label-width="formLabelWidth">
            <el-button @click="xiugaiisok" :plain="true">获取位置</el-button>
            <span>&nbsp;&nbsp;{{ form2.pos }}</span>
          </el-form-item>
          <el-form-item label="营业时间" :label-width="formLabelWidth">
            <el-input v-model="form2.openingHours" autocomplete="off">{{
              form2.openingHours
            }}</el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="bianjixiaoqu = false">取 消</el-button>
          <el-button type="primary" @click="bianjixiaoqubaocun"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <div v-else>
      <div>
        <div class="shopTopMessage">
          <div>
            <el-avatar shape="square" :size="100"></el-avatar>
          </div>
          <div class="shopTopRightMessage">
            <div class="item-column">
              <div>名称：{{ shopManagerMessage.shopName }}</div>
              <div>
                状态：{{ shopManagerMessage.shopStatus ? "上架中" : "已下架" }}
              </div>
            </div>

            <div class="item-column">
              <div>门店手机号:{{ shopManagerMessage.shopPhone }}</div>
              <div>门店详细地址：{{ shopManagerMessage.shopDescribe }}</div>
              <div>营业时间：{{ shopManagerMessage.shopDescribe }}</div>
            </div>

            <div class="item-column">
              <div>添加时间：{{ shopManagerMessage.addTime }}</div>
            </div>
          </div>
        </div>
        <div style="display: flex">
          <div style="display: flex; align-items: center">
            <span>商品名称</span>
            <div style="display: flex; width: 300px; background: aqua">
              <el-input
                id="searchName"
                placeholder="请输入内容"
                max="400"
              ></el-input>
            </div>
          </div>

          <div style="margin-left: 30px">
            <el-date-picker
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </div>
          <div style="margin-left: 30px">
            <el-button>搜索</el-button>
            <el-button @click="addGoods">新增商品</el-button>
          </div>

          <div>
            <el-dialog title="添加商品" :visible.sync="dialogFormVisibleGoods">
              <el-form :model="goodsForm">
                <el-form-item label="商品名称" :label-width="formLabelWidth">
                  <el-input
                    v-model="goodsForm.goodsName"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>

                <el-upload
                  class="upload-demo"
                  action="http://localhost:8080/goods/fileup"
                  :before-upload="handleFileUpdateBefore"
                  :data="upload"
                >
                  <el-button size="" type="primary">点击上传</el-button>
                  <!-- <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div> -->
                </el-upload>

                <el-form-item label="商品现价" :label-width="formLabelWidth">
                  <el-input
                    v-model="goodsForm.goodsPresentPrice"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisibleGoods = false"
                  >取 消</el-button
                >
                <el-button type="primary" @click="addGoodsSubmit"
                  >确 定</el-button
                >
              </div>
            </el-dialog>
          </div>
        </div>
      </div>

      <div>
        <el-table style="width: 100%" :data="shopGoodsData">
          <el-table-column prop="goodsImage" label="商品图片" width="180">
            <template slot-scope="scope">
              <img :src="goodsAvartar+scope.row.goodsImage" style="width: 35px; height:35px">
            </template>

          </el-table-column>
          <el-table-column prop="goodsName" label="商品名字" >
          </el-table-column>
          <el-table-column prop="goodsPresentPrice" label="商品现价"> </el-table-column>
          <!-- <el-table-column prop="shopxiaol" label="商品销量"> </el-table-column>
          <el-table-column prop="shopcart" label="商品购物车数量">
          </el-table-column> -->
          <el-table-column prop="action" label="操作">
            <a href="###">编辑</a>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  // components: {
  //     ElTable: Table,
  //     ElTableColumn: TableColumn,
  //     ElPagination: Pagination
  // },
  name: "MenDianComponent",
  data() {
    return {
      shopGoodsData:[],
      inputmendain: "",
      upload:{fileName:""},
      mendainphone: "",
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value1: "",
      value2: "",
      imageUrl: "",
      bianjixiaoqu: false,
      dialogFormVisible: false,
      goodsAvartar:"http://localhost:8080/goodsAvatar/",
      form: {
        mendianname: "",
        phonee: "",
        openingHours: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
        weizhi: "",
      },
      form2: {
        mendianname: "",
        phonee: "",
        openingHours: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
        weizhi: "",
        address: [],
        pos: "",
      },
      formLabelWidth: "120px",
      addressAll: [], //省市区
      address: [], //你选择的地址
      upDownArr: ["全部门店", "上架中", "已下架"],
      index: 0,
      weizhi1: "",
      weizhi2: "",
      weizhi3: "",
      weizhi4: "",
      id: "",
      tableData: [], // 表格数据
      currentPage: 1, // 当前页数
      pageSize: 10, // 每页条数
      total: 100, // 数据总数
      shopManagerMessage: {},
      flag: true,
      dialogFormVisibleGoods: false,
      goodsForm: {
        goodsName: "",
        goodsPresentPrice: "",
        shopId: 0,
        goodsUnit: "",
        goodsImage: "",
      },
      shopData: {
        salesVolume: "",
        shopAddress: "",
        shopDescribe: "",
        shopId: 0,
        shopName: "",
        shopPhone: "",
        shopStatus: 0,
      },
    };
  },

  methods: {
    addGoods() {
      console.log(this.shopManagerMessage.shopId);
      this.goodsForm.shopId = this.shopManagerMessage.shopId;
      this.dialogFormVisibleGoods = true;
    },
    addGoodsSubmit() {
      this.dialogFormVisibleGoods = false;
      console.log(this.goodsForm);
      this.$http.post("http://localhost:8080/goods/addShopGoods", {
        ...this.goodsForm,
      });
    },

    handleFileUpdateBefore(file) {
      let suffix = file.name.split(".").pop();
      let fileNewName = Date.now();
      let fullFileNewName = `${fileNewName}.${suffix}`;
      console.log(file.name);
      var file2 = new File([file], fullFileNewName, { type: file.type });
      this.goodsForm.goodsImage = file2.name;
      this.upload.fileName = file2.name;
    },
    clickUpDown(k) {
      this.index = k;
    },

    //获取省市
    getAllProvinceAndCityList() {
      // 获取全国所有省份和城市的列表
      var that = this;
      this.$http
        .get("https://restapi.amap.com/v3/config/district", {
          // 高德地图的API
          params: {
            key: "94214e26e4b0ec3a7d2ed9204f051583", // 这个是申请的 Key，读者自行写入
            keywords: "中国",
            subdistrict: 3,
            extensions: "base",
          },
        })
        .then((response) => {
          console.log(response.data);
          for (
            let i = 0;
            i < response.data.districts[0].districts.length;
            i++
          ) {
            let provinceMap = new Map();
            provinceMap.value = response.data.districts[0].districts[i].adcode; //区域编号
            provinceMap.label = response.data.districts[0].districts[i].name; //省名称
            provinceMap.children = [];
            that.addressAll.push(provinceMap); //添加省份

            for (
              let j = 0;
              j < response.data.districts[0].districts[i].districts.length;
              j++
            ) {
              let cityMap = new Map();
              cityMap.value =
                response.data.districts[0].districts[i].districts[j].adcode; //区域编号
              cityMap.label =
                response.data.districts[0].districts[i].districts[j].name; //市名称
              cityMap.children = [];
              provinceMap.children.push(cityMap); //添加市
              for (
                let k = 0;
                k <
                response.data.districts[0].districts[i].districts[j].districts
                  .length;
                k++
              ) {
                let areaMap = new Map();
                areaMap.value =
                  response.data.districts[0].districts[i].districts[
                    j
                  ].districts[k].adcode; //区域编号
                areaMap.label =
                  response.data.districts[0].districts[i].districts[
                    j
                  ].districts[k].name; //区县名称
                cityMap.children.push(areaMap); //添加区县
              }
            }
          }
        });
    },

    search() {
      if (!this.value1) {
        this.value1 = "";
      }
      this.currentPage = 1;
      this.axios
        .get("/shop/querySearchShopList?", {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            phone: this.mendainphone,
            keyword: this.inputmendain,
            shopStatus: "",
            startTime: this.getDateString(this.value1[0]),
            endTime: this.getDateString(this.value1[1]),
            communityName: this.inputmendain,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.list;
          this.total = res.data.data.total;
        })
        .catch((err) => {
          "错误";
        });
    },
    getDateString(date) {
      // let str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
      // return str;
      if (!date) {
        return "";
      }
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    huoquposition() {
      if (this.form.date1 == "") {
        this.$message.error("请填写详细地址");
      } else {
        let url =
          "https://restapi.amap.com/v3/geocode/geo?key=457886b5972a97e93fb9cdccebfd450f&address=" +
          this.address;
        this.axios(url)
          .then((res) => {
            this.form.weizhi = res.data.geocodes[0].location;
            let a = this.form.weizhi.split(",");
            this.weizhi1 = a[0];
            this.weizhi2 = a[1];
            console.log(res.data);
          })
          .catch((err) => {});
      }
    },
    isok() {
      this.axios
        .post("/shop/addShop", {
          shopAddress: this.form.date1,
          shopCity: this.address[1],
          shopDescribe: "",
          shopDistrict: this.address[2],
          shopImage: "",
          shopLatitude: this.weizhi1,
          shopLongitude: this.weizhi2,
          shopName: this.form.mendianname,
          shopPhone: this.form.phonee,
          shopProvince: this.address[0],
        })
        .then((res) => {
          this.shujuAll();
        })
        .catch((err) => {});
      this.dialogFormVisible = false;
    },
    shujuAll() {
      this.axios
        .get(
          "/shop/querySearchShopList?pageNum=" +
            this.currentPage +
            "&pageSize=" +
            this.pageSize +
            "&phone=&keyword=&shopStatus=&startTime=&endTime="
        )
        .then((res) => {
          this.tableData = res.data.data.list;
          this.total = res.data.data.total;
          // console.log(this.tableData)
          // console.log(res.data);
        })
        .catch((err) => {});
    },
    handleUploadSuccess(response, file) {
      // 处理上传成功后的响应，这里假设上传成功后返回图片的URL或者路径
      this.imageUrl = response.imageUrl; // 假设服务器返回的数据中包含 imageUrl 字段
    },
    beforeUpload(file) {
      // 可以在这里对文件进行大小、类型等验证
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
      return true; // 返回 true 允许上传，返回 false 则取消上传
    },
    //编辑
    bianjixiaoquIndex(index) {
      // console.log(this.form)
      this.form2.mendianname = index.shopName;
      // console.log(this.xiaoquguanli);
      this.form2.address = (
        index.shopProvince +
        "," +
        index.shopCity +
        "," +
        index.shopDistrict
      ).split(",");
      // console.log(this.form2.address);
      this.form2.date1 = index.shopAddress;
      // // console.log(this.addmess);
      this.form2.pos = index.shopLatitude + "," + index.shopLongitude;
      // console.log(this.form2.pos);
      this.form2.phonee = index.shopPhone;
      this.form2.openingHours = index.shopDescribe;
      this.form2.date2 = index.addTime;
      this.bianjixiaoqu = true;
      this.id = index.shopId;
    },
    bianjixiaoqubaocun() {
      this.axios
        .post("/shop/modifyShop", {
          addTime: this.form2.date2,
          concernStatus: "",
          distance: "",
          salesVolume: 0,
          shopAccount: "",
          shopAddress: this.form2.date1,
          shopCategoryList: null,
          shopCity: this.form2.address[1],
          shopCommunitySort: null,
          shopDescribe: this.form2.openingHours,
          shopDistrict: this.form2.address[2],
          shopGoodsList: null,
          shopId: this.id,
          shopImage: "",
          shopLatitude: this.weizhi3,
          shopLongitude: this.weizhi4,
          shopName: this.form2.mendianname,
          shopOrderCount: 0,
          shopPassword: null,
          shopPhone: this.form2.phonee,
          shopProvince: this.form2.address[0],
          shopSort: null,
          shopStatus: 1,
          shopUserId: 0,
        })
        .then(() => {
          this.bianjixiaoqu = false;
          this.shujuAll();
        })
        .catch((err) => {
          "错误1";
        });
    },
    xiugaiisok() {
      if (this.form2.date1 == "") {
        this.$message.error("请填写详细地址");
      } else {
        let url =
          "https://restapi.amap.com/v3/geocode/geo?key=457886b5972a97e93fb9cdccebfd450f&address=" +
          this.form2.address;
        this.axios(url)
          .then((res) => {
            this.form2.pos = res.data.geocodes[0].location;
            let a = this.form2.pos.split(",");
            this.weizhi3 = a[0];
            this.weizhi4 = a[1];
          })
          .catch((err) => {});
      }
    },
    // 切换每页条数
    handleSizeChange(size) {
      this.pageSize = size;
      // 可以在这里重新获取数据
      this.shujuAll();
    },
    // 切换当前页
    handleCurrentChange(page) {
      // this.currentPage = page;
      // 可以在这里重新获取数
      this.axios
        .get("/shop/querySearchShopList?", {
          params: {
            pageNum: page,
            pageSize: this.pageSize,
            phone: this.mendainphone,
            keyword: this.inputmendain,
            shopStatus: "",
            startTime: this.getDateString(this.value1[0]),
            endTime: this.getDateString(this.value1[1]),
            communityName: this.inputmendain,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.list;
          this.total = res.data.data.total;
        })
        .catch((err) => {
          "错误";
        });
    },
    shopManager(data) {
      this.$http.get(`/goods/getPanghuShopGoodsList?shopId=${data.shopId}`,{

      }).then((result) => {
        this.shopGoodsData = result.data.data.list;
      }).catch((err) => {

      });
      this.shopManagerMessage = data;
      this.flag = false;
    },

  },
  created() {
    this.shujuAll();
    this.getAllProvinceAndCityList();
  },
};

</script>

<style scoped>
/*门店管理*/
.shopTopMessage {
  display: flex;
}

.item-column {
  margin-left: 50px;
}

.shopTopRightMessage {
  display: flex;
}

.item-column > div {
  margin-top: 10px;
}

.mendian {
  /*height: 800px;*/
  /*background-color: yellowgreen;*/
}

.upDown {
  color: rgb(41, 255, 255);
}

.upload-demo {
  display: inline-block;
  margin-bottom: 20px;
}

.mendian {
  /*height: 100%;*/
  /*height: 800px;*/
  /*background-color: greenyellow;*/
  padding: 20px;
}

.input {
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
}

.input > div {
  margin: 20px 0;
}

span {
  font-size: 16px;
}

.shuru {
  width: 200px;
  height: 36px;
  padding: 0 15px;
}

</style>
